package jp.sourceforge.akjrcp.util.directorybased;

import java.io.IOException;

import jp.sourceforge.akjrcp.ffmpeg.FFMpegUtils;
import jp.sourceforge.akjrcp.util.ProcessMonitor;
import jp.sourceforge.akjrcp.util.ProcessPrinter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DirectoryBasedRuntimeCommand implements DirectoryBasedCommand{
	public static Log log = LogFactory.getLog(DirectoryBasedRuntimeCommand.class);
	private String[] commandString;
	private String name;
	Process process;
	ProcessPrinter processPrinter;
	private long waitForCloseStream=10000; 
	public DirectoryBasedRuntimeCommand(String name,String[] commands){
		this.name=name;
		this.commandString=commands;
	}
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String[] getCommandString() {
		return commandString;
	}

	public void setCommandString(String[] commandString) {
		this.commandString = commandString;
	}
	public int exec() throws IOException{
		if(processPrinter!=null){
		processPrinter.printOutput(FFMpegUtils.toPrintCommand(getCommandString())+"\r\n");
		}
		
		process = Runtime.getRuntime().exec(getCommandString());

		ProcessMonitor monitor=new ProcessMonitor(process,processPrinter);
		monitor.startMonitor();

			
			try {
				process.waitFor();
				long c=System.currentTimeMillis();
				while(System.currentTimeMillis()<c+waitForCloseStream){
					if(monitor.isErrorClosed() && monitor.isInputClosed()){
						break;
					}else{
						log.warn("wait:input reading");
						Thread.sleep(100);
					}
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
		return process.exitValue();
	}

	public Process getProcess() {
		
		return process;
	}

	public void setProcessPrinter(ProcessPrinter processPrinter) {
		this.processPrinter=processPrinter;
	}

}
